package icu.lookyousmileface.nio.basic;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author shenj
 * @title: NioBufferOnlyOneWriteAndRead
 * @projectName NettyPro
 * @date 2020/11/30 19:18
 */
public class NioBufferOnlyOneWriteAndRead {

    private static final String filePath1 = "src/main/resources/filedata/data1.txt";

    private static final String filePath2 = "src/main/resources/filedata/data2.txt";

    public static void main(String[] args) {

        File file1 = new File(filePath1);
        File file2 = new File(filePath2);

        try {

            FileInputStream fileInputStream = new FileInputStream(file1);
            FileOutputStream fileOutputStream = new FileOutputStream(file2);

            FileChannel fileInputStreamChannel = fileInputStream.getChannel();
            FileChannel fileOutputStreamChannel = fileOutputStream.getChannel();

            ByteBuffer dataBuffer = ByteBuffer.allocate(512);

            while (-1 != fileInputStreamChannel.read(dataBuffer)) {
                //读和写之间需要切换
                dataBuffer.flip();

                fileOutputStreamChannel.write(dataBuffer);
                //清空Buffer缓冲区的数据
                dataBuffer.clear();

            }

            fileInputStream.close();
            fileOutputStream.close();

        } catch (FileNotFoundException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }
    }
}
